
package com.craterhill.java.ems.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.PreparedStatementCreator;

import com.craterhill.java.ems.common.beans.Classes;
import com.craterhill.java.ems.dao.impl.AbstractDao;
import com.craterhill.java.ems.dao.utils.EMSResultSetExtractor;

public interface ClassesDao extends EMSDao<Classes> {

	public final String FIELD_LIST = "obj.class_id, obj.class_name, obj.class_number" + AbstractDao.MONITER_FIELDS;

	public final String FIND_ALL_CLASSES = "select " + FIELD_LIST + " from classes obj";
	public final String FIND_CLASSES = "select " + FIELD_LIST + " from classes obj where obj.class_id = ?";

	public final String SAVE_CLASSES = "insert into classes (class_name, class_number, created_by) values (?, ?, ?)";
	public final String UPDATE_CLASSES = "update classes set class_name = ?, class_number = ?, modified_date = ? where class_id = ?";
	public final String DELETE_CLASSES = "delete from classes where class_id = ?";

	public final class ClassesExtractor extends EMSResultSetExtractor<Classes> {

		@Override
		protected Classes extractResultSetData(ResultSet resultSet) throws SQLException {
			Classes classes = new Classes();
			classes.setClassesId(resultSet.getInt(1));
			classes.setClassesName(resultSet.getString(2));
			classes.setClassesNumber(resultSet.getString(3));
			classes.setStatus(resultSet.getBoolean(4));
			classes.setCreatedBy(resultSet.getInt(5));
			classes.setCreatedDate(resultSet.getDate(6));
			classes.setModifiedDate(resultSet.getDate(7));
			return classes;
		}
	}

	public final class ClassesPreparedStatementCreator implements PreparedStatementCreator {

		private final int ACTION;
		private final Classes classes;

		public ClassesPreparedStatementCreator(final int ACTION, final Classes classes) {
			this.ACTION = ACTION;
			this.classes = classes;
		}

		@Override
		public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
			PreparedStatement preparedStatement = connection.prepareStatement(this.ACTION == EMSDao.ACTION_SAVE ? SAVE_CLASSES : UPDATE_CLASSES);
			preparedStatement.setString(1, classes.getClassesName());
			preparedStatement.setString(2, classes.getClassesNumber());

			if(this.ACTION == EMSDao.ACTION_SAVE){
				preparedStatement.setInt(3, classes.getCreatedBy());
			} else{
				preparedStatement.setDate(3, classes.getModifiedDate());
				preparedStatement.setInt(4, classes.getClassesId());
			}

			return preparedStatement;
		}
	}
}
